package org.xbl.xchain.sdk.utils;

import org.xbl.xchain.sdk.amino.Codec;
import org.xbl.xchain.sdk.amino.BytesInterface;
import org.xbl.xchain.sdk.crypto.encode.Bech32;

import static org.xbl.xchain.sdk.crypto.encode.ConvertBits.convertBitsFromOrign;

public class PubkeyUtil {

    public static String Bech32ifyPubKey(String bech32PubKeyType, BytesInterface pubKeyBytes) {
        try {
            byte[] PubkeyBytes = Codec.getAmino().marshalBinaryBare(pubKeyBytes);
            byte[] base32Pubkey = convertBitsFromOrign(PubkeyBytes, (byte) 8, (byte) 5, true);
            return Bech32.encode(bech32PubKeyType, base32Pubkey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static BytesInterface decodeBech32ifyPubKey(String bech32PubKey) throws Exception {
        byte[] data = Bech32.decode(bech32PubKey).getData();
        byte[] base32Pubkey = convertBitsFromOrign(data, (byte) 5, (byte) 8, false);
        BytesInterface pubKeyBytes = (BytesInterface) Codec.getAmino().unmarshalBinaryBare(base32Pubkey, BytesInterface.class);
        return pubKeyBytes;
    }
}
